package com.czy.owner.ui.physicalorder;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.czy.owner.R;
import com.czy.owner.adapter.AddressAdapter;
import com.czy.owner.api.DeleteUserLocationApi;
import com.czy.owner.api.SaveUserLocationApi;
import com.czy.owner.api.UserLocationApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.UserLocationModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.address.AddReceiverAddress;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.lang.reflect.Type;

import butterknife.BindView;


/**
 * Created by wangyang on 2017/5/18 0018.
 * 收货地址
 */

public class AddressFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    public static final int ADDRESS = 0X11;
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView easyRecycleview;
    @BindView(R.id.ll_address_null)
    LinearLayout llAddressNull;
    private AddressAdapter addressAdapter;
    private Handler handler = new Handler();
    private boolean hasArgument2 = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_address;
    }

    @Override
    protected void initInjector() {

    }


    @Override
    protected void initViews() {
        if (getArguments() != null && getArguments().containsKey("needBack")) {
            hasArgument2 = getArguments() != null && getArguments().containsKey("needBack");
        }

        easyRecycleview.setLayoutManager(new LinearLayoutManager(getActivity()));
        addressAdapter = new AddressAdapter(getActivity(), hasArgument2);
        easyRecycleview.setAdapter(addressAdapter);
        addressAdapter.addFooter(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View view = inflater.inflate(R.layout.footer_view_address, null);
                Button btnAddress = (Button) view.findViewById(R.id.btn_add_address);

                boolean hasArgument = getArguments() != null && getArguments().containsKey("isFrom");
                if (hasArgument && getArguments().getBoolean("isFrom")) {
                    btnAddress.setText("添加联系人");
                }


                btnAddress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent ti = new Intent(getActivity(), AddReceiverAddress.class);
                        boolean hasArgument = getArguments() != null && getArguments().containsKey("isFrom");
                        boolean hasArgument2 = getArguments() != null && getArguments().containsKey("isInstall");

                        if (hasArgument && getArguments().getBoolean("isFrom")) {
                            if (hasArgument2 && !getArguments().getBoolean("isInstall")) {
                                ti.putExtra("isFrom", false);
                            } else {
                                ti.putExtra("isFrom", true);
                            }

                        }
                        ti.putExtra("isEdit", false);
                        startActivityForResult(ti, ADDRESS);
                    }
                });
                return view;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });

        addressAdapter.setOnItemSetDefaultListener(new AddressAdapter.OnItemSetDefaultListener() {
            @Override
            public void onSet(UserLocationModel.ListBean data, int position) {
                saveUserLocation(data.getUserLocationId() + "", data.getProvinceId() + "", data.getCityId() + "", data.getAreaId() + "", data.getDetailLocation(), data.getContact(), data.getContactUser(), "true");
                if (addressAdapter.getAllData().size() > 0) {
                    for (int i = 0; i < addressAdapter.getAllData().size(); i++) {
                        addressAdapter.getItem(i).setIsDefault("false");
                    }
                    addressAdapter.getItem(position).setIsDefault("true");
                    addressAdapter.notifyDataSetChanged();
                }

            }
        });

        addressAdapter.setOnItemEditListener(new AddressAdapter.OnItemEditListener() {
            @Override
            public void onEdit(UserLocationModel.ListBean data) {
                Intent ti = new Intent(getActivity(), AddReceiverAddress.class);
                ti.putExtra("isEdit", true);
                ti.putExtra("userLocationModel", data);
                startActivityForResult(ti, ADDRESS);
            }
        });

        addressAdapter.setOnItemDeleteListener(new AddressAdapter.OnItemDeleteListener() {
            @Override
            public void onDelete(final UserLocationModel.ListBean data, final int position) {
                boolean hasArgument = getArguments() != null && getArguments().containsKey("needBack");
                if (hasArgument && getArguments().getBoolean("needBack")) {
                    PhoneUtils.ShowToastMessage(getActivity(), "此处不可以删除");
                } else {
                    new UniversalDialog(getActivity()).builder().setTitle("删除收货地址")
                            .setMsg("确定删除该收货地址吗? 删除后不可恢复!")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DeleteUserLocationApi deleteUserLocationApi = new DeleteUserLocationApi(new HttpOnNextListener<String>() {
                                        @Override
                                        public void onNext(String data) {
                                            addressAdapter.remove(position);
                                            addressAdapter.notifyDataSetChanged();
                                            PhoneUtils.ShowToastMessage(getActivity(), "删除成功");
                                            if (addressAdapter.getAllData().size() == 0) {
                                                llAddressNull.setVisibility(View.VISIBLE);
                                            } else {
                                                llAddressNull.setVisibility(View.GONE);
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            super.onError(e);
                                            PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
                                        }
                                    }, (RxAppCompatActivity) (getContext()));
                                    deleteUserLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
                                    deleteUserLocationApi.setUserLocationId(data.getUserLocationId() + "");
                                    HttpManager httpManager = HttpManager.getInstance();
                                    httpManager.doHttpDeal(deleteUserLocationApi);

                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();

                }

            }
        });


        addressAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<UserLocationModel.ListBean>() {
            @Override
            public void onItemClick(View view, int position, final UserLocationModel.ListBean model) {
                boolean hasArgument = getArguments() != null && getArguments().containsKey("needBack");
                if (hasArgument && getArguments().getBoolean("needBack")) {
                    if (model.getProvinceId() == 0 || model.getCityId() == 0 || model.getAreaId() == 0) {
                        new UniversalDialog(getActivity()).builder().setTitle("请填写详细地址")
                                .setPositiveButton("确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent ti = new Intent(getActivity(), AddReceiverAddress.class);
                                        ti.putExtra("isEdit", true);
                                        ti.putExtra("userLocationModel", model);
                                        startActivityForResult(ti, ADDRESS);
                                    }
                                }).setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }).show();

                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("backType", 1);
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, model);
                        getActivity().setResult(getActivity().RESULT_OK, intent);
                        getActivity().finish();
                    }


                }

            }
        });
    }

    @Override
    protected void updateViews() {
        easyRecycleview.setRefreshListener(this);
        onRefresh();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case ADDRESS:
                    boolean isBackToConfirmOrder = data.getBooleanExtra("isBackToConfirmOrder", false);
                    if (isBackToConfirmOrder) {
                        UserLocationModel.ListBean tmpUserLocation = (UserLocationModel.ListBean) data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
                        Intent intent = new Intent();
                        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, tmpUserLocation);
                        getActivity().setResult(getActivity().RESULT_OK, intent);
                        getActivity().finish();
                    } else {
                        getDataList();
                    }

                    break;
            }

        }
    }

    private void getDataList() {
        addressAdapter.clear();
        UserLocationApi userLocationApi = new UserLocationApi(new HttpOnNextListener<UserLocationModel>() {
            @Override
            public void onNext(UserLocationModel model) {
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<UserLocationModel>>() {
                }.getType();
                BaseResultEntity<UserLocationModel> cacheList = gson.fromJson(cache, type);
                setDataList(cacheList.getData());

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                llAddressNull.setVisibility(View.GONE);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()));
        userLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(userLocationApi);
    }

    private void setDataList(UserLocationModel model) {
        if (model.getUserLocationList().size() == 0) {
            llAddressNull.setVisibility(View.VISIBLE);
        } else {
            llAddressNull.setVisibility(View.GONE);
        }
        addressAdapter.addAll(model.getUserLocationList());
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getDataList();
            }
        }, 1000);
    }

    //    设置默认地址
    private void saveUserLocation(String userLocationId, String provinceId, String cityId, String areaId, String detailLocation, String contact, String contactUser, String isDefault) {
        SaveUserLocationApi saveUserLocationApi = new SaveUserLocationApi(new HttpOnNextListener<Integer>() {
            @Override
            public void onNext(Integer data) {
                PhoneUtils.ShowToastMessage(getActivity(), "设置成功");
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) (getContext()));
        saveUserLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        saveUserLocationApi.setUserLocationId(userLocationId);
        saveUserLocationApi.setProvinceId(provinceId);
        saveUserLocationApi.setCityId(cityId);
        saveUserLocationApi.setAreaId(areaId);
        saveUserLocationApi.setDetailLocation(detailLocation);
        saveUserLocationApi.setContact(contact);
        saveUserLocationApi.setContactUser(contactUser);
        saveUserLocationApi.setIsDefault(isDefault);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(saveUserLocationApi);

    }
}
